/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 * Description: ai stats time class
 */

#include "infra/om/stats/ai_stats_time.h"

#include <sstream>

#include "infra/base/api_export.h"
#include "infra/om/stats/ai_stats_log_common.h"

namespace hiai {
int AiStatsTime::GetRunTime()
{
    auto millisecondsduration = std::chrono::duration_cast<std::chrono::milliseconds>(this->end_ - this->start_);
    auto ms = millisecondsduration.count();
    return ms;
}

INFRA_API_EXPORT std::string AiStatsTime::Now()
{
    auto n = std::chrono::system_clock::now();
    auto m = n.time_since_epoch();
    auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(m).count();
    auto ms = ((diff) % 1000); // lint !e514
    std::stringstream ss;
    std::time_t t = std::chrono::system_clock::to_time_t(n);
    char ptr[64] = {0};
    struct tm* timeinfo = std::localtime(&t);
    if (timeinfo == nullptr) {
        return std::string();
    }
    strftime(ptr, 63, "%Y-%m-%d %H.%M.%S", timeinfo);
    std::string date(ptr);
    ss << date << "." << ms;
    return ss.str();
}

uint64_t AiStatsTime::TimeNow()
{
    auto n = std::chrono::system_clock::now();
    auto m = n.time_since_epoch();
    auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(m).count();
    auto ms = ((diff) % 1000); // lint !e514
    std::time_t t = std::chrono::system_clock::to_time_t(n);

    return static_cast<uint64_t>(t * 1000 + ms);
}

std::string AiStatsTime::TimeToString(uint64_t t)
{
    std::time_t seconds = static_cast<time_t>(t / 1000UL); // lint !e514
    uint64_t ms = t % 1000; // lint !e514
    char ptr[64] = {0};
    struct tm* timeinfo;
    std::stringstream ss;
    timeinfo = std::localtime(&seconds);
    if (timeinfo == nullptr) {
        return std::string();
    }
    strftime(ptr, 63, "%Y-%m-%d %H.%M.%S", timeinfo);
    std::string date(ptr);
    ss << date << "." << ms;
    return ss.str();
}

std::string AiStatsTime::Today()
{
    auto n = std::chrono::system_clock::now();
    (void)n;
    std::time_t t = std::chrono::system_clock::to_time_t(n);
    char ptr[64] = {0};
    struct tm* timeinfo = std::localtime(&t);
    if (timeinfo == nullptr) {
        return "";
    }
    strftime(ptr, 64, "%Y%m%d", timeinfo);
    std::string date(ptr);
    return date;
}
} // end namespace hiai
